/*
 * Alarm.m
 */

#import <stdio.h>
#import "Alarm.h"

const char *months[] = {"","January","February","March","April","May","June","July","August","September","October","November","December"};

@implementation Alarm

- resetRinger
{
	gettimeofday(&tv,NULL);
	ringtime = tv.tv_sec;
	return self;
}

- findCurrentTime
{
	gettimeofday (&tv,NULL);
	localt = localtime(&tv.tv_sec);
	sec = localt->tm_sec;
	min = localt->tm_min;
	hour = localt->tm_hour;
	day = localt->tm_mday;
	month = localt->tm_mon;
	year = localt->tm_year;
	if (hour > 12)
		pm = YES;
	if (ringing)
	{
		[delegate alarm:self];
		if (tv.tv_sec - ringtime > 10 * 60) // 10 minutes
			ringing = NO;
	} 
	else if (alarmset && delegate && (hour == ahour) && (min == amin))
	{
		ringtime = tv.tv_sec;
		ringing = YES;
		[delegate alarm:self];
	}
	return self;
}

- (const char *)timeString
{
	[self findCurrentTime];
	if (hour == 0)
		hour = 12;		
	if (hour > 12)
	{
		hour -= 12;
		sprintf (timestring,"% 2d:%.2d:%.2d PM",
			hour,min,sec);
	} else  sprintf (timestring,"% 2d:%.2d:%.2d AM",
			hour,min,sec);
	return (const char *)timestring;
}

- (const char *)militaryTimeString
{
	[self findCurrentTime];
	sprintf (timestring,"% 2d:%2d:%2d",hour,min,sec);
	return (const char *)timestring;
}

- (const char *)monthString:(int) i
{
	[self findCurrentTime];
	return months[i];
}

- (const char *)dateString
{
	[self findCurrentTime];
	sprintf (timestring,"%s %d, %d",[self monthString:month],day,year);
	return timestring;
}


- (int)year
{
	[self findCurrentTime];
	return year;
}

- (int)month
{
	[self findCurrentTime];
	return month;
}

- (int)day
{
	[self findCurrentTime];
	return day;
}

- (int)hour
{
	[self findCurrentTime];
	return hour;
}


- (int)minute
{
	[self findCurrentTime];
	return min;
}


- (int)second
{
	[self findCurrentTime];
	return sec;
}

- setDelegate:sender
{
	delegate = sender;
	return self;
}

- setAlarmTime:(int)ah :(int)am
{
	ahour = ah;
	amin = am;
	return self;
}

- setAlarmState:(BOOL)astate
{
	alarmset = astate;
	if (!astate)
		ringing = NO;
	return self;
}

- (int)alarmHour
{
	return ahour;
}

- (int)alarmMinute
{
	return amin;
}

- (BOOL)alarmState
{
	return alarmset;
}

@end;